﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HtmlAgilityPack;

namespace ConsoleApp1
{
  public   class HtmlHelper
    {
        private static readonly string dir = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar;
        public static string SaveHtml(string html,string title)
        {
            
            if (!Directory.Exists(dir + Path.DirectorySeparatorChar + "html"))
            {
                Directory.CreateDirectory(dir + Path.DirectorySeparatorChar + "html");
            }
            var filename = dir + Path.DirectorySeparatorChar + "html"+Path.DirectorySeparatorChar + title + ".html";
            StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
            sw.WriteLine(html);
            sw.Flush();
            sw.Close();
            return filename;
        }

        public static string ReplaceHtml(string html)
        {
            HtmlDocument h=new HtmlDocument();
            h.LoadHtml(html);
          var imgs=h.DocumentNode.SelectNodes(@".//img");
            foreach (var img in imgs)
            {
                if (img != null)
                {
                    HtmlAttribute imgsrc = img.Attributes["src"];
                    Console.WriteLine("downloading image....:"+imgsrc.Value);
                    var localimagefile = ImageHelper.SaveImage(imgsrc.Value);
                    
                    localimagefile = "../image/" + Path.GetFileName(localimagefile);
                    html = html.Replace(imgsrc.Value.ToLower(), localimagefile.ToLower());

                }
            }


            return html;
        }
    }
}
